#include "network.h"

extern PFdProcess gFdProcess[MAX_FD];

/**
* Function    : 处理epoll事件
* @retval     : [NULL]
* Programmer  : HFauto
*/
void process_one_event(int epollfd, struct epoll_event *m_events,
                       timer_link *timerlink) {
    int fd = m_events->data.fd;

    /* 连接到达 有数据读 */
    if ((!gFdProcess[fd]->m_activeclose) && (m_events->events & EPOLLIN)) {
        if (gFdProcess[fd]->m_readfun) {
            Log << "m_readfun" << Endl;
            if (0 > gFdProcess[fd]->m_readfun(epollfd, fd, timerlink)) {
                gFdProcess[fd]->m_activeclose = true;
            }
        }
    }
    /* 有数据写 */
    if ((!gFdProcess[fd]->m_activeclose) && (m_events->events & EPOLLOUT)) {
        if (gFdProcess[fd]->m_writefun) {
            Log << "m_writefun" << Endl;
            if (0 > gFdProcess[fd]->m_writefun(epollfd, fd, timerlink)) {
                gFdProcess[fd]->m_activeclose = true;
            }
        }
    }

    if ((!gFdProcess[fd]->m_activeclose) && (m_events->events & EPOLLRDHUP)) {
        printf("events EPOLLRDHUP \n");
        gFdProcess[fd]->m_activeclose = true;
    }
    /* 关闭 */
    if (gFdProcess[fd]->m_activeclose) {
        timerlink->remote_timer(&(gFdProcess[fd]));
        gFdProcess[fd]->m_closefun(epollfd, fd, timerlink);
    }
}

/**
* Function    : 获取epoll事件
* @retval     : [NULL]
* Programmer  : HFauto
*/
void process_event(int epollfd, struct epoll_event *m_events,
                   time_value timeout, timer_link *timers) {
    int m_eventsize = epoll_wait(epollfd, m_events, MAXEPOLLEVENT, timeout); // 返回待处理事件数目与事件数组
    if (m_eventsize > 0) {
        for (int i = 0; i < m_eventsize; ++i) {
            process_one_event(epollfd, m_events + i, timers);
        }
    } else {
    }
    return;
    time_value tnow = get_now();
    // 定时器
    while (true) {
        void *point = timers->get_timer(tnow);
        if (!point) {
            break;
        }
        Log << "*****" << Endl;
        FdProcess *p = (FdProcess *)point;
        p->m_timeoutfun(epollfd, p->fd, timers, tnow);
        //		timers->add

    }
}
